import { createWriteStream } from 'node:fs'
import { fileURLToPath } from 'url'
import { pipeline, PassThrough } from 'node:stream'
import { v4 as uuidV4 } from 'uuid'
import path from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

/**
 * 支持多个文件上传
 */
export default defineEventHandler(async (event) => {
  // 使用 表单上传文件， readBody是不能解析的，它解析的是 json 格式的数据
  // let r1 = await readBody(event)

  const form = await readMultipartFormData(event)

  // form-data 里面什么都没有，这里form解析的就是 undefined
  if (!form) {
    return {
      code: 1000,
      data: null,
      message: '上传文件不存在'
    }
  }

  const allFiles = form.filter((item) => item.type)

  let filePromise = allFiles.map((item) => {
    let filename = uuidV4() + path.parse(item!.filename!).ext

    // 创建写的文件流
    const filePath = path.resolve(__dirname, '../../', `public/uploads/${filename}`)

    const wirteStream = createWriteStream(filePath)

    let data = item.data as Buffer

    // 创建一个可读流， item.data 是一个Buffer
    const readStream = new PassThrough().end(data)

    return new Promise((resolve, reject) => {
      pipeline(readStream, wirteStream, (err) => {
        if (err) {
          reject(err)
          console.log('报错了')
          console.log(err)

          return
        }

        resolve({
          url: `http://localhost:3000/uploads/${filename}`,
          type: item.type
        })
      })
    })
  })

  try {
    let res = await Promise.all(filePromise)

    return {
      code: 0,
      data: res,
      message: '上传成功'
    }
  } catch (error: any) {
    console.log('文件上传报错')
    console.log(error)
    return {
      code: 1000,
      data: null,
      message: '上传失败' + error.message
    }
  }
})
